package net.qhzw.vip.qiyu.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.DtsBarManage;
import net.qhzw.vip.qiyu.entity.DtsBarManageSecondary;
import net.qhzw.vip.qiyu.entity.DtsBarManageSecondary;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.mapper.DtsBarManageMapper;
import net.qhzw.vip.qiyu.mapper.DtsBarManageSecondaryMapper;
import net.qhzw.vip.qiyu.model.BigDataInfo;
import net.qhzw.vip.qiyu.model.DtsBarManageSecondaryExcel;
import net.qhzw.vip.qiyu.model.DtsCarRentalExcel;
import net.qhzw.vip.qiyu.service.DtsBarManageSecondaryService;
import net.qhzw.vip.qiyu.service.DtsBarManageService;
import net.qhzw.vip.qiyu.util.MyDateUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.apache.ibatis.annotations.One;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DtsBarManageSecondaryImpl extends ServiceImpl<DtsBarManageSecondaryMapper, DtsBarManageSecondary> implements DtsBarManageSecondaryService {

    @Autowired
    private DtsBarManageSecondaryMapper dtsBarManageSecondaryMapper;
    @Autowired
    private DtsBarManageService dtsBarManageService;

    @Transactional
    @Override
    public boolean addBar(DtsBarManageSecondary dtsBarManageSecondary) {
        //查询子表中是否存在一条已修理的单子
        DtsBarManageSecondary one = getOne(new LambdaQueryWrapper<DtsBarManageSecondary>().eq(DtsBarManageSecondary::getDtsBarId, dtsBarManageSecondary.getDtsBarId()).eq(DtsBarManageSecondary::getElectricCabinetCode, dtsBarManageSecondary.getElectricCabinetCode()).eq(DtsBarManageSecondary::getElectricCabinetName, dtsBarManageSecondary.getElectricCabinetName()).eq(DtsBarManageSecondary::getStatus, dtsBarManageSecondary.getStatus()));
        int update = 0;
        if (one != null) {
            // 如果有则修改
            String fileName = one.getPicture() + "," + dtsBarManageSecondary.getPicture();
            dtsBarManageSecondary.setPicture(fileName);
            dtsBarManageSecondary.setRepairNum(dtsBarManageSecondary.getRepairNum() + one.getRepairNum());
            update = dtsBarManageSecondaryMapper.update(dtsBarManageSecondary, new LambdaQueryWrapper<DtsBarManageSecondary>().eq(DtsBarManageSecondary::getId, one.getId()));
        }
        //根据dtsBarId 查询 主表中需要维修的故障及禁仓数
        DtsBarManage dtsBarManage = dtsBarManageService.getById(dtsBarManageSecondary.getDtsBarId());
        if (update > 0) {
            if (dtsBarManageSecondary.getRepairNum() == one.getProhibitedNum()) {
                DtsBarManage manage = new DtsBarManage();
                manage.setProhibitedWarehouseNum(0);
                //dtsBarManageService.update()
            }
        }
        // 否侧插入新的维修信息
        dtsBarManageSecondary.setId(IdWorker.getId());
        dtsBarManageSecondary.setElectricCabinetCode(dtsBarManageSecondary.getElectricCabinetCode());
        dtsBarManageSecondary.setElectricCabinetName(dtsBarManageSecondary.getElectricCabinetName());
        dtsBarManageSecondary.setCreated(new Date());
        dtsBarManageSecondary.setCreatedTime(new Date());
        dtsBarManageSecondary.setDtsBarId(dtsBarManageSecondary.getDtsBarId());

        if (dtsBarManageSecondary.getStatus() == 0 && dtsBarManageSecondary.getStatus() != null) {  //是故障  给故障数设置值
            dtsBarManageSecondary.setProhibitedNum(dtsBarManage.getProhibitedWarehouseNum());
            dtsBarManageSecondary.setStatus((byte) 0);
        } else {
            dtsBarManageSecondary.setFaultNum(dtsBarManage.getFaultCupboarddoorNum());//设置禁仓值
            dtsBarManageSecondary.setStatus((byte) 1);
        }

        dtsBarManageSecondary.setPosition(String.join(",", dtsBarManageSecondary.getPosition()));
        dtsBarManageSecondary.setCreated(new Date());
        dtsBarManageSecondary.setPicture(dtsBarManageSecondary.getPicture());
        if (dtsBarManageSecondary.getPositions().size() > dtsBarManage.getFaultCupboarddoorNum() || dtsBarManageSecondary.getPositions().size() > dtsBarManage.getProhibitedWarehouseNum()) {
            throw new MyException("修理的禁仓或故障不得大于本身故障数或禁仓数");
        }
        dtsBarManageSecondary.setRepairNum(dtsBarManageSecondary.getPositions().size());//设置修了几个
        boolean save = save(dtsBarManageSecondary);
        if (save) {
            //插入之后更新主表里的  故障和禁仓的总数；
            DtsBarManage dtsBarManage1 = new DtsBarManage();
            dtsBarManage1.setId(dtsBarManageSecondary.getDtsBarId());
            if (dtsBarManageSecondary.getStatus() == 0) {
                dtsBarManage1.setProhibitedWarehouseNum(dtsBarManage.getProhibitedWarehouseNum() - dtsBarManageSecondary.getPositions().size());//故障
            } else {
                dtsBarManage1.setFaultCupboarddoorNum(dtsBarManage.getFaultCupboarddoorNum() - dtsBarManageSecondary.getPositions().size());
            }
            if (dtsBarManage1.getProhibitedWarehouseNum() == 0 && dtsBarManage1.getFaultCupboarddoorNum() == 0) {
                dtsBarManage1.setStatus((byte) 0);
            }

            dtsBarManageService.updateById(dtsBarManage1);
        }
        return save;

    }

    @Override
    public boolean updateDtsBarManage(DtsBarManageSecondary dtsBarManageSecondary) {
        dtsBarManageSecondary.setCreated(new Date());
        return updateById(dtsBarManageSecondary);
    }

    @Override
    public Page<DtsBarManageSecondary> findByPage(Page<DtsBarManageSecondary> page, DtsBarManageSecondary dtsBarManageSecondary) {
        page.addOrder(OrderItem.desc("created"));
        Byte i = 0;
        Page<DtsBarManageSecondary> dtsBarPAge = page(page, new LambdaQueryWrapper<DtsBarManageSecondary>()
                .like(dtsBarManageSecondary != null && !StringUtils.isEmpty(dtsBarManageSecondary.getElectricCabinetName()), DtsBarManageSecondary::getElectricCabinetName, dtsBarManageSecondary.getElectricCabinetName())
                .eq(dtsBarManageSecondary != null && !StringUtils.isEmpty(dtsBarManageSecondary.getElectricCabinetCode()), DtsBarManageSecondary::getElectricCabinetCode, dtsBarManageSecondary.getElectricCabinetCode())
                .eq(dtsBarManageSecondary != null && !StringUtils.isEmpty(dtsBarManageSecondary.getCreated()), DtsBarManageSecondary::getCreated, dtsBarManageSecondary.getCreated())
                .eq(dtsBarManageSecondary != null && !StringUtils.isEmpty(dtsBarManageSecondary.getStatus()), DtsBarManageSecondary::getStatus, dtsBarManageSecondary.getStatus())


        );
        return dtsBarPAge;
    }

    @Transactional(rollbackFor = Exception.class)
    public void importRecharge(MultipartFile file) {
        log.error("【表格导入电柜,文件名称】: [{}]");
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);//设置一级标题行为1行
        //params.setHeadRows(1);//设置header标题为1行
        List<DtsBarManageSecondary> dtsBarManageList = null;
        try {
            dtsBarManageList = ExcelImportUtil.importExcel(file.getInputStream(), DtsBarManageSecondary.class, params);
            System.out.println("【导入总数为】: [{}]" + dtsBarManageList.size());
            if (CollectionUtils.isEmpty(dtsBarManageList)) {
                throw new MyException("电柜表格不能为空");
            } else {
                for (DtsBarManageSecondary dtsBarManageSecondary : dtsBarManageList) {
                    dtsBarManageSecondary.setId(IdWorker.getId());
                    dtsBarManageSecondary.setCreated(new Date());
                    //if (dtsBarManageSecondary.getProhibitedNum())
                    dtsBarManageSecondary.setStatus((byte) 0);
                }
            }
            //String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
            //remove(new LambdaQueryWrapper<DtsBarManageSecondary>()
            //        .eq(DtsBarManageSecondary::getCreated,time));
            saveBatch(dtsBarManageList);

        } catch (Exception e) {
            log.error("【表格导入失败】：");
            throw new MyException("表格导入失败");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addBarManageSecondary(DtsBarManageSecondary dtsBarManageSecondary) {
        //Integer total =checkGetRepairNum(dtsBarManageSecondary);
        if (dtsBarManageSecondary.getStatus() == null ){
            throw new MyException("请检查填入的数据是否有误");
        }
        DtsBarManage dtsBarManage1 = new DtsBarManage();
        //根据dtsBarId 查询 主表中需要维修的故障及禁仓数
        DtsBarManage dtsBarManage = dtsBarManageService.getById(dtsBarManageSecondary.getDtsBarId());
        //查询子表是否有已处理的故障禁仓
        DtsBarManageSecondary one=  getDtsBarManageSecondary(dtsBarManageSecondary);
        // 接收处理数据 并插入
        dtsBarManageSecondary.setUserId(SecurityUtils.getLoginUser().getUserId());
        dtsBarManageSecondary.setId(IdWorker.getId());
        //dtsBarManageSecondary.setElectricCabinetCode(dtsBarManageSecondary.getElectricCabinetCode());
        //dtsBarManageSecondary.setElectricCabinetName(dtsBarManageSecondary.getElectricCabinetName());
        dtsBarManageSecondary.setCreated(new Date());
        dtsBarManageSecondary.setCreatedTime(new Date());
        //dtsBarManageSecondary.setDtsBarId(dtsBarManageSecondary.getDtsBarId());
        dtsBarManageSecondary.setProhibitedNum(dtsBarManage.getProhibitedWarehouseNum());
        dtsBarManageSecondary.setFaultNum(dtsBarManage.getFaultCupboarddoorNum());//设置禁仓值
        if (one == null) {  //
            //1.
            //dtsBarManageSecondary.setProhibitedNum(dtsBarManage.getProhibitedWarehouseNum());
            //dtsBarManageSecondary.setFaultNum(dtsBarManage.getFaultCupboarddoorNum());//设置禁仓值
            if (dtsBarManageSecondary.getStatus() == 0 && dtsBarManageSecondary.getStatus() != null) {  //是故障  给故障数设置值
                //dtsBarManageSecondary.setProhibitedNum(dtsBarManage.getProhibitedWarehouseNum());
                dtsBarManage1.setProhibitedWarehouseNum(dtsBarManageSecondary.getProhibitedNum() - dtsBarManageSecondary.getPositions().size());//+ (one == null ? 0: one.getRepairNum())
            } else {
                //dtsBarManageSecondary.setFaultNum(dtsBarManage.getFaultCupboarddoorNum());//设置禁仓值
                dtsBarManage1.setFaultCupboarddoorNum(dtsBarManageSecondary.getFaultNum() - dtsBarManageSecondary.getPositions().size());//+ (one == null? 0: one.getRepairNum() )
            }
        }else {  //子表中 存在一条   4  2 2 2----》 2
            Integer num = checkGetRepairNum(dtsBarManageSecondary);
            //dtsBarManageSecondary.setProhibitedNum(one.getProhibitedNum());
            //dtsBarManageSecondary.setFaultNum(one.getFaultNum());//设置禁仓值
            if (dtsBarManageSecondary.getStatus() == 0 && dtsBarManageSecondary.getStatus() != null) {  //是故障  给故障数设置值

                //dtsBarManage1.setProhibitedWarehouseNum(one.getProhibitedNum() - (dtsBarManageSecondary.getPositions().size() + (one == null ? 0: one.getRepairNum()) ));
                dtsBarManage1.setProhibitedWarehouseNum(one.getProhibitedNum() - (dtsBarManageSecondary.getPositions().size() + num ));
            } else {

                dtsBarManage1.setFaultCupboarddoorNum(one.getFaultNum() - (dtsBarManageSecondary.getPositions().size() + num));
            }

        }
        dtsBarManageSecondary.setPosition(String.join(",", dtsBarManageSecondary.getPositions()));
        dtsBarManageSecondary.setCreated(new Date());
        dtsBarManageSecondary.setPicture(dtsBarManageSecondary.getPicture());
        if (dtsBarManageSecondary.getStatus() == 0 && dtsBarManageSecondary.getPositions().size() > dtsBarManage.getProhibitedWarehouseNum() ) {
            throw new MyException("修理的故障不得大于本身故障数");
        }
        if(dtsBarManageSecondary.getStatus() == 1 && dtsBarManageSecondary.getPositions().size() > dtsBarManage.getFaultCupboarddoorNum()) {
            throw new MyException("修理的禁仓不得大于本身禁仓数");
        }
        dtsBarManageSecondary.setRepairNum(dtsBarManageSecondary.getPositions().size());//设置修了几个
        boolean save = save(dtsBarManageSecondary);
        //
        if (save) {
            //插入之后更新主表里的  故障和禁仓的总数；
            //DtsBarManage dtsBarManage1 = new DtsBarManage();
            dtsBarManage1.setId(dtsBarManageSecondary.getDtsBarId());
            //if (dtsBarManageSecondary.getStatus() == 0 ) {
            //    dtsBarManage1.setProhibitedWarehouseNum(dtsBarManageSecondary.getProhibitedNum() - (dtsBarManageSecondary.getPositions().size() + (one == null ? 0: one.getRepairNum()) ));//故障
            //} else {
            //    dtsBarManage1.setFaultCupboarddoorNum(dtsBarManageSecondary.getFaultNum() - (dtsBarManageSecondary.getPositions().size()+ (one == null? 0: one.getRepairNum() )));
            //}
            List<DtsBarManageSecondary> list = dtsBarManageSecondaryMapper.selectList(new LambdaQueryWrapper<DtsBarManageSecondary>().eq(
                    DtsBarManageSecondary::getDtsBarId, dtsBarManageSecondary.getDtsBarId()
            ));
            DtsBarManageSecondary secondary = getDtsBarManageSecondary(dtsBarManageSecondary);
            if (list != null && secondary != null){
                int repairSum = list.stream().filter(d -> d.getRepairNum() != null).mapToInt(DtsBarManageSecondary::getRepairNum).sum();
               int  repairCount = secondary.getProhibitedNum() + secondary.getFaultNum();
                if (repairSum == repairCount ){
                    dtsBarManage1.setStatus((byte) 1);
                }
            }
            dtsBarManageService.updateById(dtsBarManage1);
        }

        return save;
    }

    private DtsBarManageSecondary getDtsBarManageSecondary(DtsBarManageSecondary dtsBarManageSecondary) {

        DtsBarManageSecondary one = getOne(new LambdaQueryWrapper<DtsBarManageSecondary>()
                .eq(DtsBarManageSecondary::getDtsBarId, dtsBarManageSecondary.getDtsBarId())
                .eq(DtsBarManageSecondary::getElectricCabinetCode, dtsBarManageSecondary.getElectricCabinetCode())
                .eq(DtsBarManageSecondary::getElectricCabinetName, dtsBarManageSecondary.getElectricCabinetName())
                //.eq(DtsBarManageSecondary::getStatus, dtsBarManageSecondary.getStatus())
                .orderByAsc(DtsBarManageSecondary::getCreatedTime)
                .last("limit 1"));
        return  one;
    }

    private Integer checkGetRepairNum(DtsBarManageSecondary dtsBarManageSecondary) {
        List<DtsBarManageSecondary> list = list(new LambdaQueryWrapper<DtsBarManageSecondary>()
                .eq(DtsBarManageSecondary::getDtsBarId, dtsBarManageSecondary.getDtsBarId())
                .eq(DtsBarManageSecondary::getElectricCabinetCode, dtsBarManageSecondary.getElectricCabinetCode())
                .eq(DtsBarManageSecondary::getElectricCabinetName, dtsBarManageSecondary.getElectricCabinetName())
                .eq(DtsBarManageSecondary::getStatus, dtsBarManageSecondary.getStatus())
        );
        int sum = list.stream().filter(d -> d.getRepairNum() != null).mapToInt(DtsBarManageSecondary::getRepairNum).sum();
      return sum;
    }


    @Override
    public void exportSecondary(HttpServletResponse response,DtsBarManageSecondary dtsBarManageSecondary) {
        //List<DtsBarManageSecondary> carRentalExcels = list(new LambdaQueryWrapper<DtsBarManageSecondary>()
        //        .eq(DtsBarManageSecondary::getStatus,status)
        //        .eq(DtsBarManageSecondary::getCreated,new Date()));
        List<DtsBarManageSecondaryExcel> monthSecondary = dtsBarManageSecondaryMapper.getMonthSecondary(dtsBarManageSecondary);

        //log.info("【" + MyDateUtils.getCurDt() + "租车明细：】{}", JSON.toJSONString(carRentalExcels, true));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(MyDateUtils.getCurMonth() + "修复故障禁仓明细", MyDateUtils.getCurMonth()), DtsBarManageSecondaryExcel.class, monthSecondary);

        try {
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(MyDateUtils.getCurMonth() + "修复故障禁仓明细.xls", "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);
            os.close();
            workbook.close();
        } catch (IOException e) {
            //log.error("【导出今月修复明细,错误】{}", JSON.toJSONString(e, true));
            log.error("【导出今日租车明细,错误】{}",e);
        }
    }


}
